<?php
namespace app\payclass\controller;
use app\AdminRest;

use app\ApiRest;
use app\member\model\Level;
use app\payclass\model\Active;
use app\payclass\model\Auth;
use app\payclass\model\Banner;
use app\payclass\model\Cate;
use app\payclass\model\LookRecord;
use app\payclass\model\Record;
use app\payclass\model\Video;
use app\shop\model\AdminGoods;
use app\shop\model\IndexGoods;
use think\App;

use app\payclass\model\ClassList as model;

use think\facade\Db;


class IndexClass extends ApiRest
{

    protected $model;

    protected $video_model;

    protected $banner_model;

    protected $cate_model;

    protected $look_record_model;

    protected $atv_model;

    public function __construct(App $app) {

        parent::__construct($app);

        $this->model = new Model();

        $this->video_model  = new Video();

        $this->banner_model = new Banner();

        $this->cate_model   = new Cate();

        $this->atv_model    = new Active();

        $this->look_record_model = new LookRecord();

    }

    /**
     * @author chenniang
     * @DataTime: 2020-12-09 10:15
     * @功能说明:课程首页
     */
    public function index(){

        $input = $this->_input;

        $where[] = ['uniacid','=',$this->_uniacid];

        $where[] = ['status','=',1];
        //banner图
        $data['banner_list'] = $this->banner_model->where($where)->field('jump_status,cover,jump_type,link_url')->order('top desc,id desc')->select()->toArray();
        //分类
        $data['cate_list']   = $this->cate_model->where($where)->field('id,title,cover')->order('top desc,id desc')->select()->toArray();

        $map = [

            'a.user_id' => $this->getUserId(),

            'b.status'  => 1
        ];
        //观看记录
        $data['look_record_list'] = $this->look_record_model->recordList($map);

        if(!empty($input['title'])){

            $where[] = ['title','like','%'.$input['title'].'%'];

        }
        //热门课程
        $data['class_list'] = $this->model->topClassList($where);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-12-14 11:44
     * @功能说明:分类列表
     */
    public function cateList(){

        $dis = [

            'uniacid' => $this->_uniacid,

            'status'  => 1
        ];

        $data = $this->cate_model->where($dis)->field('id,title')->order('top desc,id desc')->select()->toArray();

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-12-14 11:46
     * @功能说明:
     */
    public function classList(){

        $input = $this->_input;

        $where[] = ['uniacid','=',$this->_uniacid];

        $where[] = ['status','=',1];

        if(!empty($input['cate_id'])){

            $where[] = ['cate_id','=',$input['cate_id']];
        }

        if(!empty($input['title'])){

            $where[] = ['title','like','%'.$input['title'].'%'];
        }

        $data = $this->model->classList($where,10);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-12-14 14:55
     * @功能说明:视频详情
     */
    public function classInfo(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->model->classInfo($dis);
        //观看权限
        $data['look_auth'] = $this->model->lookAuth($data,$this->getUserId());

        $goods_model = new IndexGoods();
        //商品详情
        $data['goods_info'] = $goods_model->where(['id'=>$data['goods_id'],'status'=>1])->field('id,name,cover,price,uniacid,freight')->find();

        $video_model  = new Video();

        $atv_model    = new Active();

        $record_model = new LookRecord();
        //视频列表
        $data['video_list'] = $video_model->videoList(['class_id'=>$input['id'],'status'=>1],10,'id,title,url,text,pv');
        //集福活动
        $data['atv_info']   = $atv_model->atvInfo(['class_id'=>$input['id'],'status'=>1]);

       // dump($data['atv_info']);exit;

        $map = [

            'class_id'=> $input['id'],

            'status'  => 1
        ];
        //视频总条数
        $data['video_count'] = $video_model->where($map)->count();
        //观看记录
        $data['look_count']  = $record_model->lookCount($this->getUserId(),$data['id']);

        $member_model = new Level();

        $member = $member_model->getUserLevel($this->getUserId(),$this->_uniacid);
        //判断是否是会员
        $data['is_member'] = !empty($member)?1:0;

        $atv_record_model  = new Record();
        //查看自己的活动
        $data['user_record_id'] = $atv_record_model->myRecordId($data['id'],$this->getUserId());


        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-12-15 10:31
     * @功能说明:视频详情
     */
    public function videoInfo(){

        $input = $this->_input;

        $class = $this->model->classInfo(['id'=>$input['class_id'],'status'=>1]);

        if(empty($class)){

            $this->errorMsg('该课程已经下架');
        }
        //如果传的课程列表就查询该课程的第一部
        if(!empty($input['class_id'])){

            $data = $this->video_model->videoTopInfo(['class_id'=>$input['class_id'],'status'=>1]);

        }
        //直接查该视频
        if (!empty($input['id'])){

            $data = $this->video_model->videoInfo(['id'=>$input['id'],'status'=>1]);
        }

        if(empty($data)){

            $this->errorMsg('该视频已经下架');
        }
        //封面图
        $data['cover'] = $class['cover'];
        //观看记录
        $data['look_count'] = $this->look_record_model->lookCount($this->getUserId(),$input['class_id']);

        $arr['info'] = $data;
        //视频列表
        $arr['list'] = $this->video_model->videoSelect(['class_id'=>$input['class_id'],'status'=>1],'id,title,url');
        //查询看过得视频,看过就给一个状态
        if(!empty($arr['list'])){

            $where = [

                'user_id' => $this->getUserId(),

                'class_id'=> $input['class_id']
            ];

            $have_id = $this->look_record_model->where($where)->column('video_id');

            foreach ($arr['list'] as $k=>$v){

                $arr['list'][$k]['have_look'] = in_array($v['id'],$have_id)?1:0;

            }
        }

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-12-15 10:37
     * @功能说明:视频列表
     */
    public function videoList(){

        $input = $this->_input;

        $data  = $this->video_model->videoList(['class_id'=>$input['class_id'],'status'=>1],10,'id,title,url,text,pv');

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-12-15 15:28
     * @功能说明:活动详情
     */
    public function atvInfo(){

        $input = $this->_input;

        $dis = [

            'id' => $input['record_id']
        ];

        $record_model = new Record();
        //详情
        $data = $record_model->recordInfo($dis);

        if(empty($data)){

            $this->errorMsg('记录不存在');
        }
        //减去现在的时间
        $data['over_time']  -= time();
        //还差多少人
        $data['surplus_num'] = $data['num'] - $data['sign_num'];

        $class = $this->model->classInfo(['id'=>$data['class_id']]);
        //课程标题
        $data['class_title'] = $class['title'];
        //是否是自己的活动
        $data['is_self']     = $this->getUserId()==$data['user_id']?1:0;

        $dis = [

            'user_id'  => $this->getUserId(),

            'record_id'=> $input['record_id']

        ];

        $have = Db::name('longbing_card_payclass_record_list')->where($dis)->count();
        //查看是否已经集福过了
        $data['have_jifu'] = $have>0?1:0;
        //查看自己的活动
        $data['user_record_id'] = $record_model->myRecordId($data['class_id'],$this->getUserId());
        //记录列表
        $data['record_list'] = $record_model->recordUserList($data['id']);
        //是否已经有该视频权限
        $is_auth = $this->model->lookAuth($class,$this->getUserId());

        if($this->getUserId()==$data['user_id']){

            $data['status'] = $is_auth==1?4:$data['status'];
        }


        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-12-15 16:41
     * @功能说明:集福
     */
    public function addjifu(){

        $input = $this->_input;

        $record_model = new Record();
        //查询活动
        $record = $record_model->recordInfo(['id'=>$input['record_id']]);

        if(empty($record)){

            $this->errorMsg('活动没找到');
        }

        if($record['status']==2){

            $this->errorMsg('活动已经结束');

        }

        if($record['status']==3){

            $this->errorMsg('集福已完成');

        }

        $class = $this->model->classInfo(['id'=>$record['class_id'],'status'=>1]);

        if(empty($class)){

            $this->errorMsg('课程已下架');

        }


        $dis = [

            'user_id'  => $this->getUserId(),

            'record_id'=> $input['record_id']

        ];

        $info = Db::name('longbing_card_payclass_record_list')->where($dis)->find();

        if(!empty($info)){

            $this->errorMsg('你已经为他集过福了');

        }

        $insert = [

            'uniacid'     => $this->_uniacid,

            'user_id'     => $this->getUserId(),

            'record_id'   => $input['record_id'],

            'create_time' => time()

        ];

        Db::startTrans();

        $res = Db::name('longbing_card_payclass_record_list')->insert($insert);

        if($res!=1){

            Db::rollback();

            $this->errorMsg('集福失败');

        }

        $update = [

            'update_time' => $record['update_time']+1
        ];

        $num = Db::name('longbing_card_payclass_record_list')->where(['record_id'=>$input['record_id']])->count();
        //成功
        if($num>=$record['num']){

            $update['status'] = 3;

        }
        //利用活动的update_time做一个锁 防止并发
        $res = $record_model->where(['id'=>$input['record_id'],'update_time'=>$record['update_time']])->update($update);

        if($res!=1){

            Db::rollback();

            $this->errorMsg('集福失败');

        }

        Db::commit();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-12-16 11:31
     * @功能说明:我的课程
     */
    public function myClass(){

        $input = $this->_input;

        if($input['type']==1){

            $class = new Auth();

        }else{

            $class = new Record();
        }

        $data = $class->classList($this->getUserId(),10);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-12-16 14:34
     * @功能说明:创建活动
     */
    public function atvAdd(){

        $input = $this->_input;

        $atv   = $this->atv_model->atvInfo(['id'=>$input['atv_id'],'status'=>1]);

        if(empty($atv)){

            $this->errorMsg('活动已经下架');
        }
        //判断是否有该课程的权限
        $auth_map = [

            'class_id' => $atv['class_id'],

            'user_id'  => $this->getUserId()
        ];

        $auth_model = new Auth();

        $auth = $auth_model->authInfo($auth_map);

        if(!empty($auth)){

            $this->errorMsg('你已有该课程的权限，你无需参加该活动');

        }
        //判断是否参加了该活动
        $map[] = ['user_id','=',$this->getUserId()];

        $map[] = ['atv_id','=',$atv['id']];

        $record_model = new Record();

        $record = $record_model->where($map)->select()->toArray();

        if(!empty($record)){

            foreach ($record  as $value){
                //只有进行中 或者 已经完成的才会返回活动的id
                if($value['status']==1||$value['status']==3){

                    $this->errorMsg('你已参加该活动');
                }

            }
        }
        //课程价格
        $init_price = $this->model->where(['id'=>$atv['class_id']])->value('price');

        $insert = [

            'uniacid'    => $this->_uniacid,

            'user_id'    => $this->getUserId(),

            'atv_id'     => $atv['id'],
            //成团人数
            'num'        => $atv['num'],
            //过期时间
            'over_time'  => $atv['atv_time']+time(),

            'class_id'   => $atv['class_id'],

            'price'      => $atv['price_type']==1?$atv['price']:0,

            'auth_wx'    => $atv['auth_wx'],

            'auth_mobile'=> $atv['auth_mobile'],

            'text'       => $atv['text'],
             //课程价格
            'init_price' => $init_price,

            'staff_id'   => $input['staff_id']

        ];

        $res = $record_model->recordAdd($insert);

        $id  = $record_model->getLastInsID();

        return $this->success($id);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-12-17 17:15
     * @功能说明:领取课程 加入权限表
     */
    public function addAuth(){

        $input = $this->_input;

        $class = $this->model->classInfo(['id'=>$input['id']]);

        if(empty($class)){

            $this->errorMsg('视频已下架');

        }
        //查看可不可以领取
        $auth  = $this->model->canAddAuth($class,$this->getUserId());

        if($auth!=1){

            $this->errorMsg('该视频不可领取');
        }

        $insert = [

            'uniacid' => $this->_uniacid,

            'user_id' => $this->getUserId(),

            'class_id'=> $class['id'],

            'status'  => 1,

            'type'    => $class['watch_type']==3?3:2
        ];

        $auth_model = new Auth();

        $res = $auth_model->authAdd($insert);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-12-22 11:25
     * @功能说明:添加记录
     */
    public function addRecord(){

        $input = $this->_input;
        //增加观看量
        $this->model->where(['id'=>$input['class_id']])->update(['true_pv'=>Db::raw('true_pv+1')]);

        $dis = [

            'user_id' => $this->getUserId(),

            'class_id'=> $input['class_id'],

            'video_id'=> $input['video_id']
        ];

        $data = $this->look_record_model->recordInfo($dis);

        if(!empty($data)){

            $res = $this->look_record_model->recordUpdate(['id'=>$data['id']],['create_time'=>time()]);

        }else{

            $insert = [

                'uniacid' => $this->_uniacid,

                'user_id' => $this->getUserId(),

                'class_id'=> $input['class_id'],

                'video_id'=> $input['video_id'],

                'create_time' => time()
            ];

            $res = $this->look_record_model->insert($insert);

        }

        return $this->success($res);

    }




}
